package cn.wizzer.app.web.commons.ext.websocket.action.live.manage;

import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.models.constant.ChatConstant;
import cn.wizzer.app.web.commons.ext.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.action.NettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.result.ChatResult;
import cn.wizzer.app.web.commons.utils.NettyMsgUtil;
import cn.wizzer.app.web.commons.utils.RedisUtil;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.util.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import org.nutz.ioc.loader.annotation.IocBean;

import static cn.wizzer.app.user.modules.models.constant.ChatConstant.CHAT_USER;
import static cn.wizzer.app.web.commons.ext.websocket.main.base.TextWebSocketFrameHandler.findChannel;
import static cn.wizzer.app.web.commons.ext.websocket.main.result.ChatResult.sysSend;
@IocBean
@NettyAction(uri = "/manage/setManager")
public class SetManagerAction extends BaseNettyAction {
    @Override
    public Result action(Channel income, JSONObject params) {
        String roomId = RedisUtil.hget(User.class, ChatConstant.CHAT_USER, income.id().toString()).getRoomId();
        //用户信息
        String userStr = RedisUtil.hget(CHAT_USER, income.id().toString());
        User user = JSONUtil.parseStringToJavaBean(User.class, userStr);
        //region 权限认证
        //房主身份
        if (!roomId.startsWith(user.getId())) {
            return sysSend(ChatResult.MessageTypeEnum.SYSTEM, ChatResult.ActionEnum.REMAND, "无设置房管权限");
        }
        //目标
        String toChannel = String.valueOf(params.get("channelId"));
        User toUser = RedisUtil.hget(User.class, CHAT_USER, toChannel);
        if (toUser.isRoomManager()){
            return sysSend(ChatResult.MessageTypeEnum.SYSTEM, ChatResult.ActionEnum.ERROR,"权限不足,对方为系统默认管理员");
        }
        //endregion
        if (toUser.getManageRoom() != null && toUser.getManageRoom().contains(roomId)) {
            //region 取消房管
            toUser.getManageRoom().remove(roomId);
            RedisUtil.hset(CHAT_USER, toChannel, toUser);
            NettyMsgUtil.send(findChannel(toChannel), ChatResult.MessageTypeEnum.ACTION, ChatResult.ActionEnum.SET_MANAGE, null, "取消房管");
            return sysSend(ChatResult.MessageTypeEnum.SYSTEM, ChatResult.ActionEnum.SUCCESS,"操作成功");
            //endregion
        } else {
            //region 设为房管
            toUser.getManageRoom().add(roomId);
            RedisUtil.hset(CHAT_USER, toChannel, toUser);
            NettyMsgUtil.send(findChannel(toChannel), ChatResult.MessageTypeEnum.ACTION, ChatResult.ActionEnum.CANCEL_MANAGE, null, "设为房管");
            return sysSend(ChatResult.MessageTypeEnum.SYSTEM, ChatResult.ActionEnum.SUCCESS,"操作成功");
            //endregion
        }
    }
}
